package com.hoolai.synroom.codec;

import org.apache.log4j.Logger;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.oneone.OneToOneEncoder;
import com.google.protobuf.Message;
import com.google.protobuf.Message.Builder;
import com.hoolai.synroom.config.CmdsConfig;

public class ProtoBufEncoder extends OneToOneEncoder {
    
    private static Logger logger = Logger.getLogger("synfight");
    
     private final CmdsConfig CMDS_CONFIG;
    
    private static final String RESPOND_STRING = "<cross-domain-policy><allow-access-from domain=\"*\" to-ports=\"*\"/></cross-domain-policy>" + '\0';
    
    private final ChannelBuffer buf;
    
    public ProtoBufEncoder(CmdsConfig cmdsConfig) {
        this.CMDS_CONFIG = cmdsConfig;
        buf = ChannelBuffers.buffer(RESPOND_STRING.getBytes().length);
        buf.writeBytes(RESPOND_STRING.getBytes());
    }
    
    @Override
    protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
        if(!(msg instanceof Builder)) {
            if(msg instanceof String) {
                if(msg.equals(RESPOND_STRING)) {
                    return buf;
                }
            }
            logger.warn("someone want to send an unsupport msg type:" + msg);
            return ChannelBuffers.buffer(0);
        }
        
        Builder builder = (Builder)msg;
        Message proto = builder.build();
        int cmdId = CMDS_CONFIG.getRespCmdId(proto.getClass().getName());
        byte[] bytes = proto.toByteArray();
        ChannelBuffer buf = ChannelBuffers.buffer(5 + bytes.length);//一个整形长度，1个byte的类型
        buf.writeInt(bytes.length + 1);//数据包括 type + data
        buf.writeByte(cmdId);
        buf.writeBytes(bytes);
        
        logger.debug("------------------------------send msg--------------------------------------");
        logger.debug(proto.toString());
        logger.debug("------------------------------send msg end----------------------------------");
        
        return buf;
    }

}
